package servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oracle.net.aso.i;
import pojo.Address;
import service.AddressManeger;
import service.factory.ManagerFatory;
import util.JsonUtil;

/**
 * Servlet implementation class AjaxServlet
 */
@WebServlet("/ajax")
public class AjaxServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private AddressManeger addressManeger;
       
    public AjaxServlet() {
    	super();
    	addressManeger = ManagerFatory.getAddressManegerInstance();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<Address> list = new ArrayList<Address>();
		String search = (String) request.getParameter("search");
		list = addressManeger.findAddresses(search);
		if(list == null){
			return;
		}
		for(Address i:list){
			System.out.println(i.getName());
		}
		System.out.println(list.size());
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String test = JsonUtil.toJsonString(list);
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.getWriter().write(test);
	}
}
